package org.example.day20240904.Scott;

import org.example.day20240904.JDBCUtils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ScottInsert {
    public static void main(String[] args) throws IOException, SQLException {
        FileReader fileReader = new FileReader("emp.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        Connection connection = JDBCUtils.getConnection();

        String line = bufferedReader.readLine();
        List<Scott> scottList = new ArrayList<>();
        while (line != null){
            String[] strArr = line.split(",");
            Scott scott = new Scott(Integer.parseInt(strArr[0])
                    ,strArr[1]
                    ,strArr[2],
                    Integer.parseInt(strArr[3])
                    ,strArr[4]
                    ,Double.parseDouble(strArr[5])
                    ,Double.parseDouble(strArr[6])
                    ,Integer.parseInt(strArr[7]));
            scottList.add(scott);
            line = bufferedReader.readLine();
        }
        bufferedReader.close();
        fileReader.close();

        Collections.sort(scottList);
        Double sum = 0.0;
        for(Scott scott : scottList){
            sum += scott.sal;
        }
        Double avgSal = sum/scottList.size();

        String sql = "insert into emp (ENAME,JOB,MGR,HIREDATE,SAL,COMM,deptno) values(?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (Scott scott : scottList){
            if(scott.sal<avgSal){
                scott.sal += 1000.0;
                preparedStatement.setString(1,scott.name);
                preparedStatement.setString(2,scott.job);
                preparedStatement.setInt(3,scott.mgr);
                preparedStatement.setString(4,scott.hireDate);
                preparedStatement.setDouble(5,scott.sal);
                preparedStatement.setDouble(6,scott.comm);
                preparedStatement.setInt(7,scott.deptNo);
                preparedStatement.executeUpdate();
            }
        }
        int count = preparedStatement.getUpdateCount();
        System.out.println(count);
        JDBCUtils.close(connection,preparedStatement);
    }
}
